package guestbook;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.QueryResultList;

@SuppressWarnings("serial")
public class DeleteSensorData extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	          throws ServletException, IOException {
	
		String Table = "SensorName";
		//String Table = "CompressedData";
		int pageSize = 500;
		
		FetchOptions fetchOptions = FetchOptions.Builder.withLimit(pageSize);
		SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

		String startCursor = req.getParameter("cursor");
		// If this servlet is passed a cursor parameter, let's use it
        if (startCursor != null) {
            fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor));
        }
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
		resp.setContentType("text/html");
        //resp.setContentType("text/plain"); //if you do not want automatic page redirection
        PrintWriter o = resp.getWriter();

        Date oldDate = new Date();
        String oldDateStr = req.getParameter("oldDateStr");
        
        if (oldDateStr == null) {
        	Calendar rightNow = Calendar.getInstance();
    		rightNow.add(Calendar.MINUTE, -60);
    		oldDate = rightNow.getTime();
    		try {
				oldDate= dateFormatGmt.parse(dateFormatGmt.format(oldDate));
			} catch (ParseException e) {
				e.printStackTrace();
			}
        } else
			try {
				oldDate = dateFormatGmt.parse(URLDecoder.decode(oldDateStr, "UTF-8"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
        
		
		Query q = new Query(Table).setKeysOnly();
		q.addFilter("processed", FilterOperator.EQUAL, true); //damit nicht immer die gleichen Daten re-organisiert werden
		q.addSort("processed", Query.SortDirection.ASCENDING);
		q.addFilter("date", FilterOperator.LESS_THAN, oldDate);
		q.addSort("date", Query.SortDirection.ASCENDING); //kann nicht umgedreht werden!!!
		
        PreparedQuery pq = datastore.prepare(q);
        
        o.println("Deleting already processed entries in "+Table);
        QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
        
        List<Key> al = new ArrayList<Key>(); 
        
        for (Entity values : results ) {
        	o.println(values.getKey()+"  ");
        	al.add(values.getKey());
        }
        
        datastore.delete(al);
        o.println("<br>");

        String cursor = results.getCursor().toWebSafeString();
        if (! results.isEmpty()) {
            o.println("More to delete ..");
            o.println("<script type=\"text/javascript\">");
            o.println("<!--");
            o.println("window.location = \""+ "/del?cursor=" + cursor +"&oldDateStr="+ URLEncoder.encode(dateFormatGmt.format(oldDate), "UTF-8") +"\"");
            o.println(" //-->");
            o.println("</script>");
            
           } else o.println("<br><b>FINISHED!</b>");
	
	}
	
}
